from django.shortcuts import render,reverse
from django.http import HttpResponse
from myadmin.models import Goods,Types
from myadmin import upload
from django.contrib.auth.hashers import make_password, check_password
import os
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.

def goodsadd(request):
    db = Getall()
    return render(request,'admin/goods/add.html',{'db':db})

def goodsinsert(request):

    #实例化对象存入requset.post 对象
    # print(request.POST)
    ob = Goods()
    ob.typeid = Types.objects.get(id=request.POST['pid'])
    ob.title = request.POST['title']
    ob.price = request.POST['price']
    ob.storage = request.POST['storage']
    ob.info = request.POST['info']
    # 判断是否有图片上传
    myfile = request.FILES.get('pic',None)
    if myfile:
        newurl = upload.uploadimg(myfile)
        print(newurl)
        ob.pic = newurl
    else:
        return HttpResponse('<script>alert("商品图片不能为空");location.href="{}"</script>'.format(reverse('goods_add')))
    ob.save()
    return HttpResponse('<script>alert("商品添加成功");location.href="{}"</script>'.format(reverse('goods_list')))



def goodslist(request):
    # 价格范围搜索,商品类别下搜索,搜索结果价格排序,搜索结果销量排序,搜索结果pv排序
    # 有空再做吧.......

    #按商品标题关键字搜索
    keywords = request.GET.get('keywords','')
    # 搜索结果按时间排序
    db = Goods.objects.exclude(status=3).filter(title__contains=keywords).order_by('-addtime')
    # 获取父级分类的名称
    for i in db:
        i.pname = i.typeid.name
    # print(db[0].pname)

    #对以上操作获取的数据db做分页展示,需要引入分页类
    pageobj = Paginator(db,8)  #实例化分页对象
    # print(pageobj)
    p = int(request.GET.get('p',1)) #a标签p传参
    pdata = pageobj.page(p)   #当前页数据
    # print(pdata)
    pagelist = pageobj.page_range   #页码列表
    pageallnum = pageobj.num_pages   #直接分页对象获取总页数
    # print(pdata)
    # pageallnum = pdata.paginator.num_pages    #当前页数据也可以获取总页数
    # print(pageallnum)

    context = {'db':pdata,'pagelist':pagelist,'num':pageallnum}
    return render(request,'admin/goods/list.html',context)



def goodsedit(request,id):
    typeall = Getall()
    db = Goods.objects.get(id=id)
    typeone = db.typeid
    content={'typeall':typeall,'db':db,'typeone':typeone}
    return render(request,'admin/goods/edit.html',content)


def goodssave(request):
    #typeid不做修改
    try:
    #获取数据对象
        ob = Goods.objects.get(id=request.POST['id'])
        # print(request.POST)
        #修改常规数据
        ob.title= request.POST.get('title')
        ob.price = request.POST.get('price')
        ob.storage = request.POST.get('storage')
        ob.info = request.POST.get('info')
        #判断是否有上传突破,有上传执行上传替换.
        myfile = request.FILES.get('pic')
        if myfile:
            newurl = upload.uploadimg(myfile)
            print(newurl)
            # 删除旧的商品照片
            os.remove('.'+ob.pic)
            ob.pic = newurl
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="/admin/goods/list"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/admin/goods/edit/'+str(ob.id)+'"</script>')



def goodsdel(request,id):
    # 做逻辑删除,让其状态为下架
    try:
        ob = Goods.objects.get(id=id)
        ob.status = 3
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="{}"</script>'.format(reverse('goods_list')))
    except:
        return HttpResponse('<script>alert("删除失败");location.href="{}"</script>'.format(reverse('goods_list')))



def goodsstatus(request):
    ob = Goods.objects.get(id=request.GET['gid'])
    ob.status = request.GET['status']
    ob.save()
    return HttpResponse('')


# 获取所有分类

def Getall():
    # 不用拼接方式 防止sql注入
    ob = Types.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    for i in ob:
        # 缩进
        n = int(len(i.path)/2) - 1
        i.name = '|--'*n + i.name

        # 把所属父类的显示成字符串形式
        if i.pid == 0:
            i.pname = '顶级分类'
        else:
            # 把父类查询出来
            obj = Types.objects.get(id=i.pid)
            i.pname = obj.name

    return ob